import React, { useEffect, useState, useCallback, forwardRef, useImperativeHandle } from 'react';
import { Toast, Divider, List, InfiniteScroll, Ellipsis } from 'antd-mobile';
import { Spin } from 'antd';
import { getMessage, TextWidget } from '@inbiz/react';
import { getPreView } from '@inbiz/utils';
import NoData from '../NoData';
import { getApplyList, getApplyCategory } from '../ProcessApply/service';
import { getToMe, getMyToDo, getMyApply, getHaveDone, getClassification } from '../service';
import { getAssignList } from '../ProcessAssigned/service';
import { getWillAssignList } from '../ProcessWillAssign/service';
import { getTasks } from '../ProcessReceive/service';
import { getDraft } from '../ProcessDraft/service';
import { processState, goto, formatTime, formatProcessName } from '../../commonUtils';
import TitleLogo from './TitleLogo';
import EasyViewGroupItem from './EasyViewGroupItem';
import ProcessMore from '../assets/icons/processMore';
import GroupPopup from './GroupPopup';

const EsayViewItem = forwardRef((props: any, ref) => {
  const { processData, activeTab, ...others } = props;
  const {
    showMore,
    easyLoadMoreLocation,
    easyAssociatePage,
    easyLoadMoreText,
    userInfo,
    processGroup,
    rangeConfig,
    pageSize,
    h5_listLogo,
    h5_showStatus,
    keyToType,
  } = others;
  const [loading, setLoading] = useState(false);
  const [curGroup, setCurGroup] = useState(getMessage('processCenter.all'));
  const [groups, setGroups] = useState<any[]>([]);
  const [dropdownGroups, setDropdownGroups] = useState<any[]>([]);
  const [groupsIndex, setGroupsIndex] = useState(0);
  const [hasMore, setHasMore] = useState(false);
  const [data, setData] = useState([]);
  const [requestDone, setRequestDone] = useState(false);
  const [pageIndex, setPageIndex] = useState(1);
  const [groupPopupVisible, setGroupPopupVisible] = useState(false);

  const getGroupData = async (userId: string, rangeConfig: string, processGroup: any) => {
    let params = {
      userId: userId,
      type: 'apply',
      groupType: 'Group',
      dptKey:
        rangeConfig == 'all' || processGroup?.selectedRows?.length == 0
          ? ''
          : processGroup?.groupGuid ?? '',
    };
    let results = await getApplyCategory(params);
    if (results?.code == '200' && results?.details?.GroupData?.length > 0) {
      setGroups(
        [{ name: getMessage('processCenter.all'), id: getMessage('processCenter.all') }].concat(
          results?.details?.GroupData,
        ),
      );
    } else {
      setGroups([]);
    }
  };

  const getProcessData = async (
    userId: string,
    rangeConfig: string,
    processGroup: any,
    pageSize: number,
    processGroupName: string,
    curId: string,
    _pageIndex?: number,
  ) => {
    let params = {
      userId,
      pageIndex: _pageIndex || pageIndex,
      pageSize,
      processGroupName,
      dptKey:
        rangeConfig == 'all' || processGroup?.selectedRows?.length == 0
          ? ''
          : processGroup?.groupGuid ?? '',
    };
    if (curId != '1') {
      params['starter'] = userId;
    }
    let results: any;
    // setLoading(true);
    switch (curId) {
      case '1':
        results = await getApplyList(params);
        break;
      case '2':
        results = await getMyToDo(params);
        break;
      case '3':
        params['isunderApplication'] = true;
        results = await getMyApply(params);
        break;
      case '6':
        params['isunderApplication'] = false;
        results = await getMyApply(params);
        break;
      case '4':
        results = await getDraft(params);
        break;
      case '5':
        results = await getToMe(params);
        break;
      case '7':
        results = await getHaveDone(params);
        break;
      case '8':
        results = await getClassification(params);
        break;
      case '9':
        results = await getAssignList(params);
        break;
      case '10':
        results = await getWillAssignList(params);
        break;
      case '11':
        results = await getTasks(params);
        break;
      default:
        results = [];
        break;
    }
    if (results?.code == '200' && results?.details?.rows?.length > 0) {
      let _data = results?.details?.rows?.map((item: any) => {
        return {
          ...item,
          taskState:
            curId == '5'
              ? item.taskState == '170' || item.taskState == '180'
                ? item.taskState ?? '0'
                : '150'
              : item.taskState || item.processState || 0,
        };
      });
      if (showMore) {
        setData(_data);
      } else {
        setData((prev) => prev.concat(_data));
        setPageIndex((prev) => prev + 1);
        setHasMore(pageSize * (_pageIndex || pageIndex) < results?.details?.total);
      }
    } else {
      setData([]);
    }
    // setLoading(false);
    setRequestDone(true);
  };

  const onLoadMore = () => {
    if (easyAssociatePage) {
      let path = easyAssociatePage.split(',')[0];
      window.location.href = getPreView(path) + `/${keyToType}?type=mobile&tabKey=${activeTab}`;
    } else {
      // 请联系管理员配置关联页面
      Toast.show({
        content: getMessage('processCenter.associatedPageIsNotConfigured'),
      });
    }
  };

  const goDetail = (item: any, e: any) => {
    let params =
      activeTab == '4'
        ? {
          processDefinitionId: item.procDefId,
          businessKey: item.businessKey,
          drafID: item.draftsId,
          inItiateApplication: true,
          taskState: item.taskState,
          siteType: 1,
        }
        : activeTab == '1'
          ? {
            processDefinitionId: item.processDefinitionId,
            inItiateApplication: true,
            siteType: 1,
          }
          : {
            taskIds: item.taskId,
            processInstanceId: item.processInstanceId,
            inItiateApplication: false,
            drafID: item.draftsId,
            taskState: item.taskState,
            siteType: 1,
          };
    goto(params, activeTab, 'wap', e, '', () => {
      getProcessData(
        userInfo?.ID,
        rangeConfig,
        processGroup,
        pageSize,
        curGroup == getMessage('processCenter.all') ? '' : curGroup,
        activeTab,
      );
    });
  };

  const processRenderItem = useCallback(
    (item: any) => {
      if (processData?.id == '1') {
        return (
          <>
            <div className="processCenter-h5-easy-item-process-item-title-wrapper">
              <div
                className="processCenter-h5-easy-item-process-item-title"
                onClick={(e) => {
                  goDetail(item, e);
                }}
              >
                <div className="processCenter-h5-easy-item-process-item-title-content">
                  <Ellipsis direction="end" content={item?.ProcessName} />
                </div>
                <div className="processCenter-h5-easy-item-process-item-desc">{`（v${item?.ProcessVersion}）`}</div>
              </div>
            </div>
            <div className="processCenter-h5-easy-item-process-item-group">{item?.groupName}</div>
          </>
        );
      } else {
        return (
          <>
            <div className="processCenter-h5-easy-item-process-item-title-wrapper">
              <div className="processCenter-h5-easy-item-process-item-title">
                <div
                  className="processCenter-h5-easy-item-process-item-title-content"
                  onClick={(e) => {
                    if (
                      processData?.id == '9' ||
                      processData?.id == '10' ||
                      processData?.id == '11'
                    ) {
                      return;
                    }
                    goDetail(item, e);
                  }}
                >
                  <Ellipsis direction="end" content={formatProcessName(activeTab, item)} />
                </div>
                {processData?.id != '4' &&
                  processData?.id != '9' &&
                  processData?.id != '10' &&
                  processData?.id != '11' &&
                  h5_showStatus && (
                    <div
                      style={{
                        width: 50,
                        height: 24,
                        color: processState[item?.taskState]?.stateFontColor ?? '',
                        background: processState[item?.taskState]?.stateBgColor || '',
                        lineHeight: '24px',
                        borderRadius: '4px',
                        textAlign: 'center',
                        fontSize: 12,
                        marginLeft: 12,
                      }}
                    >
                      <TextWidget>
                        {item?.taskState
                          ? processState[item?.taskState]?.stateName
                          : processState['0']?.stateName}
                      </TextWidget>
                    </div>
                  )}
              </div>
            </div>
            <div className="processCenter-h5-easy-item-process-item-time">
              {formatTime(
                item?.taskCreateTime ||
                item?.processStartTime ||
                item?.creationTime ||
                item?.taskStartTime ||
                item?.processCreateTime ||
                item?.startTime,
              )}
            </div>
          </>
        );
      }
    },
    [processData],
  );

  const setActiveGroup = (name: string) => {
    setCurGroup(name);
  };

  useEffect(() => {
    if (activeTab == '1' && processData?.processGroup) {
      getGroupData(userInfo?.ID, rangeConfig, processGroup);
    }
  }, [userInfo?.ID, rangeConfig, activeTab, processData?.processGroup]);

  useImperativeHandle(ref, () => ({
    getData: () => {
      if (activeTab == '1' && processData?.processGroup) {
        getGroupData(userInfo?.ID, rangeConfig, processGroup);
      }
      getProcessData(
        userInfo?.ID,
        rangeConfig,
        processGroup,
        pageSize,
        curGroup == getMessage('processCenter.all') ? '' : curGroup,
        activeTab,
        1,
      );
    },
  }));

  useEffect(() => {
    setRequestDone(false);
    setData([]);
    setPageIndex(1);
  }, [showMore, curGroup, processGroup]);

  useEffect(() => {
    if (showMore) {
      getProcessData(
        userInfo?.ID,
        rangeConfig,
        processGroup,
        pageSize,
        curGroup == getMessage('processCenter.all') ? '' : curGroup,
        activeTab,
        1,
      );
    } else {
      getProcessData(
        userInfo?.ID,
        rangeConfig,
        processGroup,
        pageSize,
        curGroup == getMessage('processCenter.all') ? '' : curGroup,
        activeTab,
        1,
      );
    }
  }, [pageSize, curGroup, showMore, processGroup]);

  useEffect(() => {
    if (groups?.length > 0) {
      let groupItems = document.getElementsByClassName('processCenter-h5-easy-group-item');
      let _index = 0;
      for (let i = 0; i < groupItems.length; i++) {
        let _offsetLeft = groupItems[i]?.offsetLeft;
        if (_offsetLeft === 0 && i != 0) {
          _index = i;
          break;
        }
      }
      if (_index != 0) {
        let _disdance = groupItems[_index - 1].offsetLeft + groupItems[_index - 1].offsetWidth + 20;
        let fatherWidth = document.getElementsByClassName('processCenter-h5-easy-group')[0]
          .offsetWidth;
        if (fatherWidth <= _disdance + 28) {
          _index = _index - 1;
        }
        setGroupsIndex(_index);
        let _dropdownGroups = groups?.filter((item: any, index: number) => index >= _index);
        _dropdownGroups = _dropdownGroups?.map((item1: any) => {
          return {
            key: item1?.id,
            label: item1?.name,
          };
        });
        setDropdownGroups(_dropdownGroups);
      } else {
        setDropdownGroups([]);
        setGroupsIndex(999);
      }
    }
  }, [groups]);

  return (
    <div className="processCenter-h5-easy-item-wrapper">
      {processData?.processGroup && (
        <div className="processCenter-h5-easy-group">
          {groups?.map((item, index) => {
            return (
              <EasyViewGroupItem
                key={item?.name}
                groupItemData={item}
                curGroup={curGroup}
                setActiveGroup={setActiveGroup}
                displayNone={index >= groupsIndex}
              />
            );
          })}
          {dropdownGroups?.length > 0 && (
            <div
              className="processCenter-h5-easy-group-more"
              onClick={(e) => {
                setGroupPopupVisible(true);
              }}
            >
              {React.createElement(ProcessMore)}
            </div>
          )}
        </div>
      )}
      <div className="processCenter-h5-easy-item-process">
        <Spin spinning={loading}>
          <List>
            {data && data?.length > 0 ? (
              data?.map(
                (item: {
                  ProcessName: string;
                  taskId: string;
                  processInstanceId: string;
                  draftsId: string;
                }) => {
                  return (
                    <List.Item
                      key={
                        processData?.id == '1'
                          ? item?.ProcessName
                          : (item.taskId || item.processInstanceId || item.draftsId) +
                          processData?.id || ''
                      }
                    >
                      {h5_listLogo && <TitleLogo listLogo={h5_listLogo} />}
                      {processRenderItem(item)}
                    </List.Item>
                  );
                },
              )
            ) : requestDone ? (
              <NoData />
            ) : null}
            {!showMore && requestDone && data && data?.length > 0 && (
              <InfiniteScroll
                loadMore={() =>
                  getProcessData(
                    userInfo?.ID,
                    rangeConfig,
                    processGroup,
                    pageSize,
                    curGroup == getMessage('processCenter.all') ? '' : curGroup,
                    activeTab,
                  )
                }
                hasMore={hasMore}
              >
                {!hasMore && <TextWidget>processCenter.noMore</TextWidget>}
              </InfiniteScroll>
            )}
            {showMore &&
              easyLoadMoreLocation == 'bottomMiddle' &&
              requestDone &&
              data &&
              data?.length > 0 && (
                <div className="processCenter-h5-easy-item-more">
                  <Divider>
                    <div style={{ padding: 0, fontSize: 12 }} onClick={onLoadMore}>
                      <TextWidget>{easyLoadMoreText}</TextWidget>
                    </div>
                  </Divider>
                </div>
              )}
          </List>
        </Spin>
      </div>
      <GroupPopup
        groups={dropdownGroups}
        visible={groupPopupVisible}
        setVisible={setGroupPopupVisible}
        setActiveGroup={setActiveGroup}
        curGroup={curGroup}
      />
    </div>
  );
});

export default EsayViewItem;
